<template>
    <div>
        <center>
        <table>
            <tr v-for="i in user" :key="i.id">
                <td>账户的初始金额为: {{i.money}} </td>
            </tr>
            <tr>
                <td>
                    <button @click="getdian">获取用电量</button>
                </td>
            </tr>
            <tr>
                <td>
                    请输入金额 <input type="text" v-model="num"><button @click="add">充值</button>
                </td>
            </tr>
            <tr>
                <button @click="Do">结算</button>
            </tr>
        </table>
        </center>
    </div>
</template>

<script>
export default {
    name: 'MyHome',
    data() {
        return {
            user:{
                name:"",
                money:""
            },
            num:""
        };
    },
    props: {},

    components: {},

    created() {},

    mounted() {
        this.getuser()
    },

    methods: {
        getuser(){
            let name = localStorage.getItem('username')
            this.axios.get('http://127.0.0.1:8000/check/' + name + '/')
            .then(res => {
                this.user = res.data.data
            })
            .catch(err => {
                alert(err)
            })
        },
        getdian(){
            let name = localStorage.getItem('username')
            this.axios.get('http://127.0.0.1:8000/shengcheng/'+ name +'/')
            .then(res => {
                if(res.data.code == 200){
                    alert('电量是>>>>'+res.data.num)
                }else{
                    alert(res.data.msg)
                }
            })
            .catch(err => {
                alert(err)
            })
        },
        add(){
            let name = localStorage.getItem('username')
            this.axios.post('http://127.0.0.1:8000/add/' + name  + '/',{
            num:this.num
           })
           .then(res => {
            alert('成功',res)
           }) 
           .catch(err => {
                alert(err)
                console.log(name)
           })
        },
        Do(){
            let name = localStorage.getItem('username')
            this.axios.put('http://127.0.0.1:8000/sub/' + name + '/')
            .then(res => {
                if(res.data.code == 200){
                    alert("结算成功,余额为：",res.data.data)
                }else{
                    alert(res.data.msg)
                }
            })
            .catch(err => {
                alert(err)
            })
        }
    },

    computed: {},

    watch: {},

    directives: {},

    filters: {}
};
</script>

<style scoped>
* {
    margin: 0;
}
</style>
